package com.itheima.health.controller;

import com.github.pagehelper.util.StringUtil;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.util.Map;
@RestController
@RequestMapping("/mobile/login")
@Slf4j
public class LoginController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberService memberService;

    @PostMapping("/smsLogin")
    public Result login(@RequestBody Map map, HttpServletRequest request){

        String telephone = map.get("telephone").toString();
        //获取验证码
        String validateCode = map.get("validateCode").toString();
        String  code = redisTemplate.opsForValue().get(telephone).toString();

        //进行验证码的比对
        if(!StringUtils.isEmpty(code) &&validateCode.equals(code)){
            Member member = new Member();
            member.setPhoneNumber(telephone);
            member = memberService.createOrUpdate(member);

            redisTemplate.delete(telephone);

            request.setAttribute("member",member);
            log.info("登陆成功");
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        }
        return new Result(false, MessageConst.LOGIN_FAIL);
    }
}
